package net.loyin;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.google.gson.Gson;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * 
 * @author 刘声凤
 * 2014年3月2日
 */
public class Generator {

	public static void main(String[] args) {
		String appDir=Generator.class.getResource("/").toString().replace("file:/", "").replace("/bin", "");
		appDir=URLDecoder.decode(appDir);
		System.out.println(appDir);
		String dataDir=appDir+"data";
		System.out.println(dataDir);
		String tempDir=appDir+"template";
		System.out.println(tempDir);
		try {
			Date now=new Date();
			String author="刘声凤";
			String email="loyin@loyin.net";
			String basepackage="net/loyin";
			Configuration cfg=new Configuration();
			File tempDirFile=new File(tempDir);
			cfg.setDirectoryForTemplateLoading(tempDirFile);
			File[] dataList=new File(dataDir).listFiles();
			File[] tempList=tempDirFile.listFiles();
			if(dataList!=null&&dataList.length>0){
				for(File f:dataList){
					Map<String,Object>map=new HashMap<String,Object>();
					/**分析资源文件*/
					parseDataFile(f,map);
					System.out.println(new Gson().toJson(map));
					for(Map<String,Object> m:(Set<Map<String,Object>>)map.get("tblist")){//循环读取表
						m.put("author", author);
						String tbname=(String)m.get("tbname");//表名
						String[] tt_=tbname.split("_");//取总包 如sys_user则会分成 sys user
						m.put("DIR", basepackage+"/"+tt_[0].toLowerCase());
						m.put("basepackage",basepackage);
						m.put("package",tt_[0].toLowerCase()+"."+tt_[1].toLowerCase());
						m.put("dir",tt_[0].toLowerCase()+"/"+tt_[1].toLowerCase());
						m.put("className", StringKit.firstCharToUpperCase(tt_[1]));
						m.put("now",now);
						m.put("basepackagedot",basepackage.replaceAll("/", "."));
						System.out.println(new Gson().toJson(m));
						for(File ftl:tempList){
							if(ftl.isDirectory())//至对模版目录下的目录生成
							/**写入模版*/
							writeFile(ftl, cfg, m);
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 根据模版写文件
	 * */
	public static void writeFile(File f,Configuration cfg,Map<String,Object>map) throws Exception{
		if(f.isFile()){
			Template template=new Template("", new FileReader(f),cfg);
			StringWriter sout=new StringWriter();
			Template fpathtemp=new Template("", new StringReader(f.getPath()),cfg);
			fpathtemp.process(map, sout);
			File outf=new File(sout.toString().replace("template","output"));
			outf.getParentFile().mkdirs();
			Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outf),"UTF-8"));
			sout.close();
			template.process(map, out);
		}else if(f.isDirectory()){
			File[] fs=f.listFiles();
			if(fs!=null&&fs.length>0)
			for(File f_:fs){
				writeFile(f_,cfg,map);
			}
		}
	}
	/**分析data文件*/
	public static void parseDataFile(File dataFile,Map<String,Object>map){
		try {
			BufferedReader reader=new BufferedReader(new FileReader(dataFile));
			String line=null;
			/**先读取前三行数据*/
			String sxfg=reader.readLine();//属性分隔符
			System.out.println("属性分隔符"+sxfg);
			String bfg=reader.readLine();//表格分隔符
			System.out.println("属性分隔符"+bfg);
			String sxline=reader.readLine();
			String[] sx=sxline.split(sxfg);//属性
			System.out.println("属性分隔符"+sxline);
			//表集合
			Set<Map<String,Object>> tblist=new HashSet<Map<String,Object>>();
			//表
			Map<String,Object> table=null;
			List<Map<String,Object>> cls=new ArrayList<Map<String,Object>>();
			while((line=reader.readLine())!=null){
				if("".equals(line)){
					break;
				}
				if(bfg.equals(line)){//表结束
					table.put("cls",cls);//添加列
					tblist.add(table);
					cls=new ArrayList<Map<String,Object>>();
				}else if(line.startsWith(bfg)){//判断表开始
					table=new HashMap<String,Object>();
					String[] tt=line.split(sxfg);
					table.put("tbname",tt[0].replace(bfg,""));//表名
					table.put("tbcname", tt[1]);//表中文名
				}else{
					String[] sxlist=line.split(sxfg);//获取属性
					int i=0;
					System.out.println(line+"\t"+sxlist.length);
					Map<String,Object> clounm=new HashMap<String,Object>();
					for(String sx_:sxlist){
						Object o=sx_;
						if("true".equals(sx_.toLowerCase())||"false".equals(sx_.toLowerCase())){
							o=Boolean.parseBoolean(sx_);
						}
						clounm.put(sx[i++], o);
					}
					cls.add(clounm);
				}
			}
			if(cls.isEmpty()==false)
			table.put("cls",cls);//添加列
			tblist.add(table);
			reader.close();
			map.put("tblist",tblist);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
}
